package com.xlh.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimaps;
import com.xlh.common.Result;
import com.xlh.util.SpringContextUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;

/**
 * 课程导入WebSocket
 *
 * @author lx
 */
@ServerEndpoint(value = "/ws/course/convert-tool", configurator = GetHttpSessionConfigurator.class)
@Component
public class CourseImportWebsocket {

    private static final Logger LOGGER = LoggerFactory.getLogger(CourseImportWebsocket.class);

    private static final ObjectMapper objectMapper = SpringContextUtil.getBean(ObjectMapper.class);

    private static ListMultimap<Long, CourseImportWebsocket> connectionMap = Multimaps.synchronizedListMultimap(ArrayListMultimap.create());

    private Session session;

    private Long userId;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.session = session;
        this.userId = (Long) config.getUserProperties().get("userId");
        connectionMap.put(userId, this);
    }

    @OnClose
    public void onClose() {
        connectionMap.remove(userId, this);
    }

    @OnMessage
    public void onMessage(String jsonStr, Session session) {
        // 暂时不需要实现该方法
    }

    @OnError
    public void onError(Session session, Throwable error) {
        // 暂时不需要实现该方法
    }

    /**
     * 发送消息
     *
     * @param userId  分享人Id
     * @param message 消息内容
     */
    private static void sendMessage(Long userId, String message) {
        List<CourseImportWebsocket> courseImportWebsockets = connectionMap.get(userId);
        if (CollectionUtils.isNotEmpty(courseImportWebsockets)) {
            for (CourseImportWebsocket courseImportWebsocket : courseImportWebsockets) {
                try {
                    courseImportWebsocket.getSession().getBasicRemote().sendText(message);
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 发送消息
     *
     * @param userId 接收消息用户
     * @param result 消息内容
     */
    public static void sendMessage(Long userId, Result result) {
        try {
            String sendMessage = objectMapper.writeValueAsString(result);
            sendMessage(userId, sendMessage);
        } catch (JsonProcessingException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    public Session getSession() {
        return session;
    }

}
